﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[RequireComponent(typeof(Camera))]
public class InputPhysicsRaycaster : InputRaycasterBase {

	protected Camera m_EventCamera;

	private RaycastHit[] m_Hits;

	protected LayerMask m_EventMask = -1;

	public override Camera eventCamera {
		get {
			if (this.m_EventCamera == null) {
				this.m_EventCamera = GetComponent<Camera> ();
			}
			return this.m_EventCamera ?? Camera.main;
		}
	}

	public int finalEventMask
	{
		get
		{
			return this.eventCamera == null ? -1 : (this.eventCamera.cullingMask & this.m_EventMask); //-1为111111111
		}
	}

	public LayerMask eventMask
	{
		get
		{
			return this.m_EventMask;
		}
		set
		{
			this.m_EventMask = value;
		}
	}

	protected void ComputeRayAndDistance(InputEventData eventData, out Ray ray, out float distanceToClipPlane)
	{
		ray = this.eventCamera.ScreenPointToRay(eventData.Position);
		float z = ray.direction.z;
		//如果z等于0，那么距离为很大
		distanceToClipPlane = ((Mathf.Approximately(0f, z)) ? float.PositiveInfinity : Mathf.Abs((this.eventCamera.farClipPlane - this.eventCamera.nearClipPlane) / z));
	}

	public override void Raycast (InputEventData eventData, List<stRaycastResult> resultAppendList)
	{
		//Debug.LogError (this.eventCamera.pixelRect);
		//Debug.LogWarning (eventData.Position);
		if (this.eventCamera != null && this.eventCamera.pixelRect.Contains (eventData.Position)) {
			Ray r;
			float disToClip;
			this.ComputeRayAndDistance (eventData, out r, out disToClip);
			//Debug.LogWarning (disToClip);
			int num;
			this.m_Hits = Physics.RaycastAll (r, disToClip, this.eventMask);
			num = this.m_Hits.Length;
			//Debug.LogError (num);
			if (num > 1) {
				Array.Sort<RaycastHit> (this.m_Hits, (RaycastHit r1, RaycastHit r2) => r1.distance.CompareTo (r2.distance));
			}
			if (num > 0) {
				int i = 0;
				while (i < num) {
					stRaycastResult item = new stRaycastResult {
						gameObject = this.m_Hits [i].collider.gameObject,
						module = this,
						distance = this.m_Hits [i].distance,
						worldPosition = this.m_Hits [i].point,
						worldNormal = this.m_Hits [i].normal,
						screenPosition = eventData.Position,
						index = (float)resultAppendList.Count,
						sortingLayer = 0,
						sortingOrder = 0
					};
					resultAppendList.Add (item);
					i++;
				}
			}
		}
	}
}
